package com.security.sdk.handler;

import com.security.sdk.config.JWTConfig;
import com.security.sdk.entity.TokenEntity;
import com.security.sdk.entity.UserEntity;
import com.security.sdk.utils.JWTTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 登录成功处理类
 * @Author lhc
 * @CreateTime 2020/10/3 9:13
 */
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JWTConfig jwtConfig;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse,
                                         Authentication authentication) throws IOException, ServletException {
        // 组装JWT
        UserEntity userEntity =  (UserEntity) authentication.getPrincipal();
        String token = JWTTokenUtil.createToken(userEntity, jwtConfig);
        token = jwtConfig.getTokenPrefix() + token;
        // 封装返回参数
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code","200");
        resultData.put("msg", "登录成功");
        resultData.put("token",token);
    }
}
